package com.yingjia.yingjiauniversity.retrofit.convert;

import com.yingjia.basic.common.util.GenericReflectUtil;
import com.yingjia.basic.http.convert.ConvertorManager;
import com.yingjia.basic.http.convert.IConvert;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Created by 张智轶 on 2016/10/9.
 */
public class CommonJsonConverterFactory extends Converter.Factory {
    public static CommonJsonConverterFactory create() {
        return new CommonJsonConverterFactory();
    }

    protected Logger logger = LoggerFactory.getLogger(((Object) this).getClass());

    private CommonJsonConverterFactory() {
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        IConvert convert = ConvertorManager.getInstance().getGlobalConvert(GenericReflectUtil.getGenericTypeName(type), GenericReflectUtil.getGenericTypeName(RequestBody.class));
        if (convert != null && convert instanceof Converter) {
            return (Converter) convert;
        } else {
            return new ObjectRequestBodyConverter();
        }
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        IConvert convert = ConvertorManager.getInstance().getGlobalConvert(GenericReflectUtil.getGenericTypeName(ResponseBody.class), GenericReflectUtil.getGenericTypeName(type));
        if (convert != null && convert instanceof Converter) {
            return (Converter) convert;
        } else {
            return new ObjectResponseBodyConverter(type);
        }

    }
}
